package action.newelifile;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.commons.net.ftp.FTPFile;

import action.adapter.FtpItemServerAdapter;
import action.pojo.FtpConnect;
import action.pojo.LocalFilePojo;
import action.util.LoadSetting;
import action.util.Tool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MainFTPActivity extends Activity {
	Button expandButton,addressButton,switchButton,backButton,changeViewButton,uploadButton,sortButton,multiButton,mBackButton,
	mCopyButton,mCutButton,mDeleteButton,mCancelButton,downloadButton;
	ImageView imageView1,imageView2,imageMobile,imageSdcard;
	GridView gridView;
	ListView listView,listDetailView;
	TextView txtViewEmpty;

	LinearLayout expandLayout;
	Dialog dialog;

	FtpConnect ftpConnect = new FtpConnect();
	ArrayList<FtpConnect> list_ftp;
	FTPFile[] listfileFTP;
	FtpItemServerAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		try{
			Tool.position = 3;
			LoadSetting.load(this);
			initLocale();
			setContentView(R.layout.main);
			initAttribute();
			ftpConnect = (FtpConnect) getIntent().getExtras().get("ftp");
			list_ftp= new ArrayList<FtpConnect>();
			initData();
			LoadSetting.loadTheme(this);
			processButton();
			super.onCreate(savedInstanceState);
		}catch (Exception e) {
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}
	public void initLocale(){
		String languageToLoad = Tool.locale(LoadSetting.setting.getLanguage());  
		Locale locale = new Locale(languageToLoad);   
		Locale.setDefault(locale);  
		Configuration config = new Configuration();  
		config.locale = locale;  
		getBaseContext().getResources().updateConfiguration(config,   
				getBaseContext().getResources().getDisplayMetrics());  


	}
	public void initAttribute(){
		expandButton = (Button)findViewById(R.id.expandButton);
		addressButton = (Button)findViewById(R.id.addressButton);
		switchButton = (Button)findViewById(R.id.switchButton);
		backButton = (Button)findViewById(R.id.backButton);
		changeViewButton = (Button)findViewById(R.id.changeViewButton);
		uploadButton = (Button)findViewById(R.id.uploadButton);
		downloadButton = (Button)findViewById(R.id.downloadButton);
		sortButton = (Button)findViewById(R.id.sortButton);
		multiButton = (Button)findViewById(R.id.multiButton);
		mBackButton = (Button)findViewById(R.id.mBackButton);
		mCopyButton = (Button)findViewById(R.id.mCopyButton);
		mCutButton = (Button)findViewById(R.id.mCutButton);
		mDeleteButton = (Button)findViewById(R.id.mDeleteButton);
		mCancelButton = (Button)findViewById(R.id.mCancelButton);

		imageView1 = (ImageView)findViewById(R.id.imageView1);
		imageView2 = (ImageView)findViewById(R.id.imageView2);
		imageMobile = (ImageView)findViewById(R.id.imageMobile);
		imageSdcard = (ImageView)findViewById(R.id.imageSdcard);

		gridView = (GridView)findViewById(R.id.gridView);

		listView = (ListView)findViewById(R.id.listView);
		listDetailView = (ListView)findViewById(R.id.listDetailView);

		txtViewEmpty = (TextView)findViewById(R.id.txtViewEmpty);

		expandLayout = (LinearLayout)findViewById(R.id.expandLayout);

		imageSdcard.setImageResource(R.drawable.ftp);
		switchButton.setText("FTP");

		uploadButton.setVisibility(Button.GONE);
		downloadButton.setVisibility(Button.VISIBLE);
	}

	public void initData(){
		Tool.ftp_path = new ArrayList<String>();
		Tool.ftp_path.add(File.separator);
		
		refreshItemServerFTP();
	}

	public void refreshItemServerFTP() {
		if (Tool.ftp_path.size() == 0) {
			expandButton.setClickable(false);
		} else {
			expandButton.setClickable(true);
		}
		try {
//			Tool.HOST = ftpConnect.getHostname();
//			Tool.PORT = ftpConnect.getPort();
//			Tool.USER = ftpConnect.getUsername();
//			Tool.PASS = ftpConnect.getPassword();
			
			boolean flag = Tool.connects();
			System.out.println(" flag == " + flag);
			if(flag){
				listfileFTP= Tool.client.listFiles(Tool.getFTPPath(Tool.ftp_path));
				System.out.println("size: "+listfileFTP.length);
				if(listfileFTP!=null && listfileFTP.length>0){
					ArrayList<FtpConnect> ffile = new ArrayList<FtpConnect>();
					ArrayList<FtpConnect> ffolder = new ArrayList<FtpConnect>();
					for(FTPFile f : listfileFTP){
						FtpConnect tem = new FtpConnect();
						Drawable icon = null;
						if(f.isFile()){
							if (Tool.checkExtendFile(f.getName(),
							".txt")
							|| Tool.checkExtendFile(
									f.getName(), ".csv")) {
								icon = getResources()
								.getDrawable(
										R.drawable.text_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".xml")) {
								icon = getResources()
								.getDrawable(
										R.drawable.xml_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".flv")
									|| Tool.checkExtendFile(
											f.getName(), ".3gp")
											|| Tool.checkExtendFile(
													f.getName(), ".avi")) {										
								icon = getResources().getDrawable(R.drawable.video_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".mp3")) {
								icon = getResources()
								.getDrawable(
										R.drawable.mp3_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".doc")
									|| Tool.checkExtendFile(
											f.getName(), ".docx")) {
								icon = getResources()
								.getDrawable(
										R.drawable.word_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".ppt")
									|| Tool.checkExtendFile(
											f.getName(), ".pptx")) {
								icon = getResources()
								.getDrawable(
										R.drawable.pptx_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".xls")
									|| Tool.checkExtendFile(
											f.getName(), ".xlsx")) {
								icon = getResources()
								.getDrawable(
										R.drawable.xlsx_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".zip")
									|| Tool.checkExtendFile(
											f.getName(), ".rar")) {
								icon = getResources()
								.getDrawable(
										R.drawable.rar_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".jpg")
									|| Tool.checkExtendFile(
											f.getName(), ".jpeg")
											|| Tool.checkExtendFile(
													f.getName(), ".png")
													|| Tool.checkExtendFile(
															f.getName(), ".bmp")
															|| Tool.checkExtendFile(
																	f.getName(), ".gif")) {
								icon = getResources().getDrawable(R.drawable.image_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".apk")) {
								icon = getResources()
								.getDrawable(
										R.drawable.apk_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".exe")) {
								icon = getResources()
								.getDrawable(
										R.drawable.exe_file);
							} else {
								icon = getResources()
								.getDrawable(
										R.drawable.unknown_file);
							}

							tem.setHostname(ftpConnect.getHostname());
							tem.setPort(ftpConnect.getPort());
							tem.setUsername(ftpConnect.getUsername());
							tem.setPassword(ftpConnect.getPassword());
							tem.setIcon(icon);
							tem.setFtpFile(f);
							ffile.add(tem);
						}else if(f.isDirectory()){
							icon = getResources().getDrawable(R.drawable.folder_ftp);
							tem.setHostname(ftpConnect.getHostname());
							tem.setPort(ftpConnect.getPort());
							tem.setUsername(ftpConnect.getUsername());
							tem.setPassword(ftpConnect.getPassword());
							tem.setIcon(icon);
							tem.setFtpFile(f);
							
							ffolder.add(tem);
						}
					}

					//sap xep

					//add list lon
					list_ftp.clear();
					if(ffolder!=null && ffolder.size()>0)
						list_ftp.addAll(ffolder);
					
					if(ffile!=null && ffile.size()>0)
						list_ftp.addAll(ffile);

					System.out.println(" ftp files ==  " + listfileFTP.length);
					switch (LoadSetting.setting.getDisplay()) {
					case 0:
						initalGridView();
						break;
					case 1:
						initalListView();
						break;
					case 2:
						initalDetailView();
						break;
					default:
						break;
					}	
				}
			}
			else{
				System.out.println(" connect fail");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			Tool.closeconnect();
		}
//		addressButton.setText(Tool.HOST+Tool.getFTPPath(Tool.ftp_path));
	}

	private void initalListView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.VISIBLE);
		listDetailView.setVisibility(ListView.GONE);
		txtViewEmpty.setVisibility(TextView.GONE);
		if(list_ftp!=null && list_ftp.size()>0){
			adapter = new FtpItemServerAdapter(this, R.layout.list_view, list_ftp);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(onListFileClick());
			//			listView.setOnItemLongClickListener(itemLongClick());
		}else{
			listView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}

	private void initalGridView() {
		gridView.setVisibility(GridView.VISIBLE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.GONE);
		txtViewEmpty.setVisibility(TextView.GONE);
		if(list_ftp!=null && list_ftp.size()>0){
			adapter = new FtpItemServerAdapter(this, R.layout.list_view, list_ftp);
			gridView.setAdapter(adapter);
			gridView.setOnItemClickListener(onListFileClick());
			//			gridView.setOnItemLongClickListener(itemLongClick());
		}else{
			gridView.setVisibility(GridView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}

	private void initalDetailView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.VISIBLE);
		txtViewEmpty.setVisibility(TextView.GONE);

		if(list_ftp!=null && list_ftp.size()>0){
			adapter = new FtpItemServerAdapter(this, R.layout.list_view, list_ftp);
			listDetailView.setAdapter(adapter);
			listDetailView.setOnItemClickListener(onListFileClick());
			//			listDetailView.setOnItemLongClickListener(itemLongClick());
		}else{
			listDetailView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}
	
	public OnItemClickListener onListFileClick(){
		OnItemClickListener onclick = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				FtpConnect connect = (FtpConnect)arg0.getItemAtPosition(arg2);
				Tool.ftp_path.add(connect.getFtpFile().getName());
				refreshItemServerFTP();
			}
			
		};
		return onclick;
	}
	// process button
	public void processButton(){
		expandButton.setOnClickListener(processButtonExpand());
		backButton.setOnClickListener(processButtonBack());
		addressButton.setOnClickListener(processButtonAddress());
		switchButton.setOnClickListener(processSwitchButton());
	}
	// process button expand
	public OnClickListener processButtonExpand(){
		OnClickListener onclick = new  View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if(expandLayout.getVisibility()==LinearLayout.GONE){
					expandLayout.setVisibility(LinearLayout.VISIBLE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.subtract), null,null);
				}else{
					expandLayout.setVisibility(LinearLayout.GONE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.plus), null,null);
				}
			}
		};
		return onclick;
	}

	// process button back
	public OnClickListener processButtonBack(){
		OnClickListener action = new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		};
		return action;
	}

	// process button address
	public OnClickListener processButtonAddress(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				Tool.list_favorite = getFavorite();
				Intent intent = new Intent(getApplicationContext(), AddressActivity.class);
				startActivity(intent);
			}
		};
		return onclick;
	}


	private ArrayList<LocalFilePojo> getFavorite() {
		Tool.list_favorite = new ArrayList<LocalFilePojo>();

		return Tool.list_favorite;
	}


	private OnClickListener processSwitchButton() {
		OnClickListener action = new OnClickListener() {

			public void onClick(View v) {
				String[] list = new String[] { "Local", "LAN", "FTP" };
				dialog = new Dialog(MainFTPActivity.this);
				dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
				dialog.setContentView(R.layout.popup_switch);
				((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.switch_to);
				ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
				listview.setAdapter(new ArrayAdapter<String>(MainFTPActivity.this,
						android.R.layout.select_dialog_singlechoice, list));
				listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listview.setItemChecked(2, true);
				listview.setOnItemClickListener(switchToClick());
				((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		};
		return action;
	}
	private OnItemClickListener switchToClick() {
		OnItemClickListener action = new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//				Intent intent = null;
				System.out.println("arg == " + arg2);
				if (arg2==0) {
					Intent intent = new Intent(MainFTPActivity.this, LocalActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					return;
				}if (arg2==1){
					Intent intent = new Intent(MainFTPActivity.this, LanActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					return;
				}if (arg2==2){
					dialog.dismiss();
					return;
				}
				dialog.dismiss();
				finish();
			}
		};
		return action;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_ftp, menu);
		setMenuBackground();
		return super.onCreateOptionsMenu(menu);
	}

	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  

			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.color.menu_option_background);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_setting:
			Intent intent = new Intent(MainFTPActivity.this,SettingActivity.class);
			startActivity(intent);
			break;
		case R.id.menu_operator:
			break;
		case R.id.menu_new:
			processNewFolder();
			break;
			/*case R.id.menu_search:
			break;*/
		case R.id.menu_refresh:
			break;
		case R.id.menu_quit:
			runExit();
			break;
		}
		return true;
	}

	private void runExit(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.exitapp));
		builder.setMessage(getString(R.string.questionexitapp));
		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				MainFTPActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	public void processNewFolder(){
	}
}
